<?php
/**
 * 导出模型数据，存储为.qbtcmf格式
 */

namespace plugins\qbt_custom_model\service;

use think\Db;

class ExportService
{
    private $path = "";
    private $sql = "";

    public function __construct()
    {
        $this->path = str_replace("\\", DS, dirname(__DIR__)) . DS . 'data' . DS;
    }

    /**
     * 导出空数据模型
     */
    public function export_empty_model($ids)
    {
        $model_arr = Db::name("model")->where("model_id", "in", $ids)->select()->toArray();
        foreach ($model_arr as $k => $v) {
            $this->export_models($v);
            $this->export_model_field($v['model_id']);
            $this->export_model_table($v);
        }
        $file_name = $this->path . 'backup' . DS . 'model.sql';
        //开始写入文件
        $res = file_put_contents($file_name, $this->sql);
        if ($res !== false) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 导出带数据模型
     */
    public function export_data_model($ids)
    {
        $filename = $this->path . 'backup' . DS . 'model.zip';
        $model_arr = Db::name("model")->where("model_id", "in", $ids)->select()->toArray();
        //文件名数组
        $file_arr = [];
        foreach ($model_arr as $k => $v) {
            $this->export_models($v);
            $this->export_model_field($v['model_id']);
            $this->export_model_table($v);
            $this->export_model_table_data($v);
        }
        $file_name = $this->path . 'backup' . DS . 'model.sql';
        //开始写入文件
        file_put_contents($file_name, $this->sql);
        $zip = new \ZipArchive();
        if ($zip->open($filename, \ZIPARCHIVE::CREATE) === TRUE) {
            $zip->addEmptyDir('controller');
            $zip->addEmptyDir('model');
            $zip->addEmptyDir('validate');
            $zip->addEmptyDir('upload');
            $zip->addfile($file_name, 'model.sql');
            foreach ($model_arr as $k => $v) {
                $this->export_zip($v, $zip);
//                createZip(opendir(UPLOAD_LOCAL_ROOT),$zip,UPLOAD_LOCAL_ROOT);
            }
            $zip->close();//关闭
            return true;
        }
        return false;
    }

    /**
     * 获取文件名，并加入
     */
    private function export_zip($model_arr, $zip)
    {
        $name = $model_arr['model_controller'];
        $ctrl_name = $name . 'Controller.php';
        $mdl_arr = explode("_", $model_arr['model_tabname']);
        $mname = '';
        $model_name = '';
        $validate = '';
        if (count($mdl_arr) > 1) {
            foreach ($mdl_arr as $v) {
                $mname .= ucfirst($v);
            }
            $model_name = $mname . "Model.php";
            $validate = $mname . "Validate.php";
        } else {
            $model_name = ucfirst($model_arr['model_tabname']) . "Model.php";
            $validate = ucfirst($model_arr['model_tabname']) . "Validate.php";
        }
        $str = preg_replace("/([A-Z])/", "_\\1", $name);
        //去除第一个_
        $str = strtolower(ltrim($str, "_"));
        $addfile  = CMF_ROOT . "public/themes/admin_simpleboot3/admin/" . $str . "/add.html";
        $editfile = CMF_ROOT . "public/themes/admin_simpleboot3/admin/" . $str . "/edit.html";
        $listfile = CMF_ROOT . "public/themes/admin_simpleboot3/admin/" . $str . "/index.html";
        #nsh 20190108 增加图片单独打包
        $model_field = Db::name('model_field')->where('model_id', $model_arr['model_id'])->select();
        $data = Db::name($model_arr['model_tabname'])->select()->toArray();
        foreach ($data as $data_val) {
            foreach ($model_field as $item) {
                if ($item['field_type'] == 'image' || $item['field_type'] == 'file') {
                    if (!empty($data_val[$item['field_name']])) {
                        $dir_list = explode('/',$data_val[$item['field_name']]);
                        array_pop($dir_list);
                        $name = '';
                        foreach ($dir_list as $d_val){
                            $name.='/'.$d_val;
                            $zip->addEmptyDir('upload'.$name);
                        }
                        $zip->addfile( ROOT_PATH  .'public'.DS. 'upload' . DS .$data_val[$item['field_name']],'upload'.DS.$data_val[$item['field_name']]);
                        $name = null;
                    }
                }elseif ($item['field_type'] == 'images' || $item['field_type'] == 'files'){
                    if (!empty($data_val[$item['field_name']])) {
                        $images = json_decode($data_val[$item['field_name']],true);
                        foreach ($images as $i){
                            $img_key[]=$i['url'];
                        }
                        foreach ($img_key as $im){
                            $dir_list = explode('/',$im);
                        array_pop($dir_list);
                        $name = '';
                        foreach ($dir_list as $d_val){
                            $name.='/'.$d_val;
                            $zip->addEmptyDir('upload'.$name);
                        }
                        $zip->addfile( ROOT_PATH  .'public'.DS. 'upload' . DS .$im,'upload'.DS.$im);
                        $name = null;
                        }
                    }
                }
            }
        }
        $zip->addfile(APP_PATH . 'admin' . DS . 'controller' . DS . $ctrl_name, 'controller' . DS . $ctrl_name);
        $zip->addfile(APP_PATH . 'admin' . DS . 'model' . DS . $model_name, 'model' . DS . $model_name);
        $zip->addfile(APP_PATH . 'admin' . DS . 'validate' . DS . $validate, 'validate' . DS . $validate);

        $vdir = 'view' . DS . $str . DS;
        $zip->addEmptyDir($vdir);
        $zip->addfile($addfile, $vdir . 'add.html');
        $zip->addfile($editfile, $vdir . 'edit.html');
        $zip->addfile($listfile, $vdir . 'index.html');

    }

    /**
     * 导出模型信息
     */
    public function export_models($model_arr)
    {
        $str = "INSERT INTO " . config("database.prefix") . "model VALUES ";
        $arr = [];
        foreach ($model_arr as $k => $v) {
            $arr[] = "'" . $v . "'";
        }
        $arr[0] = "null";
        $str .= "(" . implode(",", $arr) . ");\n";
        $this->sql .= $str;
        return $this->sql;
    }

    /**
     * 导出模型对应字段信息
     */
    public function export_model_field($model_id)
    {

        $field_arr = Db::name("model_field")->where(["model_id" => $model_id])->select()->toArray();
        $arr = [];
        foreach ($field_arr as $key => $value) {
            foreach ($value as $q) {
                $arr[$key][] = "'" . $q . "'";
            }
        }
        foreach ($arr as $k => $v) {
            $str = "INSERT INTO " . config("database.prefix") . "model_field VALUES ";
            $v[0] = "null";
            $str .= "(" . implode(",", $v) . ");\n";
            $this->sql .= $str;
        }
        return $this->sql;
    }

    /**
     * 导出模型对应的表结构
     */
    public function export_model_table($model_arr)
    {
        $sql = "show create table " . config("database.prefix") . $model_arr['model_tabname'];
        $res = Db::query($sql);
        $this->sql .= $res[0]["Create Table"] . ";\n";
        return $this->sql;
    }

    /**
     * 导出对应表数据
     */
    public function export_model_table_data($model_arr)
    {
        $tabarr = Db::name($model_arr['model_tabname'])->select()->toArray();
        $arr = [];
        foreach ($tabarr as $key => $value) {
            foreach ($value as $q) {
                $arr[$key][] = "'" . $q . "'";
            }
        }
        foreach ($arr as $k => $v) {
            $str = "INSERT INTO " . config("database.prefix") . "model_field VALUES ";
            $v[0] = "null";
            $str .= "(" . implode(",", $v) . ");\n";
            $this->sql .= $str;
        }
        return $this->sql;
    }


}